"""报告查询相关的数据模型"""

from datetime import datetime
from enum import Enum
from typing import List, Optional

from pydantic import BaseModel, Field, validator


class ReportType(str, Enum):
    """报告类型枚举"""
    LABORATORY = "0"  # 检验报告
    EXAMINATION = "1"  # 检查报告


class PatientType(str, Enum):
    """患者类型枚举"""
    OUTPATIENT = "1"  # 门诊患者
    INPATIENT = "2"  # 住院患者


class ReportStatus(str, Enum):
    """报告状态枚举"""
    REGISTERED = "registered"  # 已登记
    CALLED = "called"  # 已叫号
    CHECKED = "checked"  # 已检查
    SUBMITTED = "submitted"  # 已提交
    REVIEWED = "reviewed"  # 已审核
    RESCINDED = "rescinded"  # 已撤销
    CANCELLED = "cancelled"  # 已取消
    REJECTED = "rejected"  # 已驳回
    PASSED = "passed"  # 已过号


class SpecialReportType(str, Enum):
    """特殊报告类型枚举"""
    NUCLEIC_ACID_SINGLE = "NucleicAcidSingleTesting"  # 核酸单检
    NUCLEIC_ACID_MIXED = "NucleicAcidMixedTesting"  # 核酸混检
    MICROBIOLOGICAL_POSITIVE = "MicrobiologicalTestingPositive"  # 微生物检测阳性
    MICROBIOLOGICAL_NEGATIVE = "MicrobiologicalTestingNegative"  # 微生物检测阴性


class ReportMainQueryRequest(BaseModel):
    """报告主信息查询请求模型"""

    medical_card_number: str = Field(..., description="就诊卡号", example="11009009")
    id_card: str = Field(..., description="身份证号", example="370101200001010001")
    admission_number: Optional[str] = Field(None, description="住院号", example="0652585")
    patient_type: Optional[str] = Field(None, description="患者类型：1门诊，2住院，空串返回所有")
    start_time: str = Field(..., description="开始时间，格式：yyyy-MM-dd HH:mm:ss", example="2018-01-01 18:00:00")
    end_time: str = Field(..., description="结束时间，格式：yyyy-MM-dd HH:mm:ss", example="2018-01-02 18:00:00")
    patient_name: str = Field(..., description="就诊人姓名", example="王震")
    hospital_id: Optional[str] = Field(None, description="医院ID，多个用英文逗号分隔", example="001,002,003")

    @validator('id_card')
    def validate_id_card(cls, v):
        """验证身份证号格式"""
        if not v or len(v) != 18:
            raise ValueError('身份证号必须为18位')
        return v

    @validator('start_time', 'end_time')
    def validate_datetime_format(cls, v):
        """验证时间格式"""
        try:
            datetime.strptime(v, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            raise ValueError('时间格式必须为：yyyy-MM-dd HH:mm:ss')
        return v

    @validator('hospital_id')
    def validate_hospital_ids(cls, v):
        """验证医院ID格式"""
        if v:
            hospital_ids = v.split(',')
            for hospital_id in hospital_ids:
                if not hospital_id.strip():
                    raise ValueError('医院ID格式错误')
        return v

    model_config = {
        "json_schema_extra": {
            "example": {
                "medical_card_number": "11009009",
                "id_card": "370101200001010001",
                "admission_number": "0652585",
                "patient_type": "1",
                "start_time": "2018-01-01 18:00:00",
                "end_time": "2018-01-02 18:00:00",
                "patient_name": "王震",
                "hospital_id": "001,002,003"
            }
        }
    }


class ReportInfo(BaseModel):
    """报告信息模型"""

    hospital_id: str = Field(..., description="医院ID")
    id: str = Field(..., description="报告唯一标识")
    type: ReportType = Field(..., description="报告类型：0检验，1检查")
    time: str = Field(..., description="报告审核时间，格式：yyyy-MM-dd HH:mm:ss")
    doctor: str = Field(..., description="审核报告的医生姓名")
    item: str = Field(..., description="项目名称")
    special_types: Optional[SpecialReportType] = Field(None, description="特殊报告类型")
    status: Optional[ReportStatus] = Field(None, description="报告状态")
    is_empty: str = Field("0", description="1敏感报告，0普通报告")
    pdf_url: Optional[str] = Field(None, description="PDF报告链接地址")

    model_config = {
        "json_schema_extra": {
            "example": {
                "hospital_id": "253",
                "id": "1001",
                "type": "0",
                "time": "2018-02-01 18:20:20",
                "doctor": "王春霞",
                "item": "血常规",
                "special_types": "NucleicAcidSingleTesting",
                "status": "reviewed",
                "is_empty": "1",
                "pdf_url": "https://www.example.com/pdfReportxxxx"
            }
        }
    }


class ReportMainQueryResponse(BaseModel):
    """报告主信息查询响应模型"""

    success: bool = Field(..., description="接口成功返回true，失败返回false")
    msg: str = Field(..., description="成功返回成功或空，失败返回错误信息")
    code: str = Field(..., description="返回代码，参照接口规范")
    data: dict = Field(..., description="响应数据")

    model_config = {
        "json_schema_extra": {
            "example": {
                "success": True,
                "msg": "成功",
                "code": "10001",
                "data": {
                    "patient_name": "张之路",
                    "report": [
                        {
                            "hospital_id": "253",
                            "id": "1001",
                            "type": "0",
                            "time": "2018-02-01 18:20:20",
                            "doctor": "王春霞",
                            "item": "血常规",
                            "special_types": "NucleicAcidSingleTesting",
                            "status": "reviewed",
                            "is_empty": "1",
                            "pdf_url": "https://www.example.com/pdfReportxxxx"
                        }
                    ]
                }
            }
        }
    }


class ErrorResponse(BaseModel):
    """错误响应模型"""

    success: bool = Field(False, description="接口成功标志")
    msg: str = Field(..., description="错误信息")
    code: str = Field(..., description="错误代码")
    data: Optional[dict] = Field(None, description="额外数据")

    model_config = {
        "json_schema_extra": {
            "example": {
                "success": False,
                "msg": "身份证号不能为空",
                "code": "60501",
                "data": None
            }
        }
    }